import { Link, useNavigate } from "react-router-dom";
import { useContext, useEffect, useState } from "react";
import { UserContext } from "../context/userContext";
import axios from "axios";
import dayjs from "dayjs";
import {Avatar, Button, Form, Input, List, Space} from "antd-mobile";

const UserInfo = () => {
  const [avatar, setAvatar] = useState('');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [createdAt, setCreatedAt] = useState(null);
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmNewPassword, setConfirmNewPassword] = useState('');
  const [error, setError] = useState('');
  const [isAvatarTouched, setIsAvatarTouched] = useState(false);
  const [isChangePwd, setIsChangePwd] = useState(false);

  const navigate = useNavigate();
  const { currentUser } = useContext(UserContext);
  const token = currentUser?.token;

  const cancel = () => {
    navigate(-1);
  }
  useEffect(() => {
    if (!token) {
      navigate('/login');
    }
  }, [token, navigate]);

  useEffect(() => {
    const getUser = async () => {
      if (!currentUser?.id) {
        console.log('no user id')
        return;
      }
      try {
        const response = await axios.get(
          `${process.env.REACT_APP_BASE_URL}/users/${currentUser.id}`,
          { withCredentials: true, headers: { Authorization: `Bearer ${token}` } }
        );

        const { name, email, avatar, createdAt } = response.data;
        setName(name);
        setEmail(email);
        setAvatar(avatar);
        setCreatedAt(createdAt);
      } catch (error) {
        console.log(error);
      }
    };

    getUser();
  }, [currentUser?.id, token]);

  const changeAvatarHandler = async (file) => {

    setIsAvatarTouched(false);

    try {
      const postData = new FormData();
      postData.set('avatar', file);
      console.log(postData.get('avatar'))
      const response = await axios.post(
        `${process.env.REACT_APP_BASE_URL}/users/change-avatar`,
        postData,
        { withCredentials: true, headers: { Authorization: `Bearer ${token}` } }
      );
      setAvatar(response?.data.avatar);
      navigate(-1)
    } catch (error) {
      console.log(error);
    }
  };

  const updateUserDetails = async (e) => {
    e.preventDefault();

    try {
      const userData = { name, email, currentPassword, newPassword, confirmNewPassword };

      const response = await axios.patch(
        `${process.env.REACT_APP_BASE_URL}/users/edit-user`,
        userData,
        { withCredentials: true, headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.status === 200) {
        navigate(-1);
      }
    } catch (error) {
      setError(error.response.data.message);
    }
  };

  return <section className="profile">
    <Form
        layout='horizontal'
        footer={
      <Space block direction="horizontal" justify='around'  wrap >
          <Button onClick={cancel} style={{'--background-color': 'rgba(80, 62, 157, 0.1)', '--text-color':'rgba(80, 62, 157, 1)', '--border-style':'none', 'width':'120px'}} block type='cancel' color='primary' size='large'>
            取消
          </Button>
          <Button onClick={updateUserDetails} style={{'--background-color': 'rgba(80, 62, 157, 1)', '--text-color':'white', '--border-style':'none', 'width':'190px'}} block type='submit' color='primary' size='large'>
            保存
          </Button>
      </Space>
        }
    >
      <Form.Header>基本资料</Form.Header>
      <List.Item onClick={() => {
        setIsAvatarTouched(true)
      }} extra={isAvatarTouched?<form>
        <input
            type="file"
            name="avatar"
            id="avatar"
            onChange={async (e) => {
              console.log(e.target.files[0]);
              await changeAvatarHandler(e.target.files[0])
            }}
            accept="png, jpg, jpeg"
        />
        <label htmlFor="avatar" onClick={() => setIsAvatarTouched(true)}></label>
      </form>:<Avatar src={`${process.env.REACT_APP_ASSETS_URL}/uploads/${avatar}`} alt=""/>}>头像</List.Item>

      <Form.Item
          name='name'
          label='昵称'
          childElementPosition='right'
      >
        <Input defaultValue={currentUser?.name} onChange={val => setName(val)} placeholder='请输入昵称'/>
      </Form.Item>
      <List.Item extra={currentUser?.id}>账号 ID </List.Item>
      <List.Item extra={ createdAt?dayjs(createdAt).format('YYYY-MM-DD'):''}  >创建时间</List.Item>

      <List header='账号安全'>
        <List.Item extra={email}  >邮箱 </List.Item>
        {isChangePwd?<>
          <Form.Item
              name='currentPassword'
              label='原密码'
              childElementPosition='right'
          >
            <Input onChange={val => setCurrentPassword(val)} placeholder='请输入您设置的原密码'/>
          </Form.Item>
          <Form.Item
              name='newPassword'
              label='新密码'
              childElementPosition='right'
          >
            <Input onChange={val => setNewPassword(val)} placeholder='请设置新密码'/>
          </Form.Item>
          <Form.Item
              name='confirmPassword'
              label='密码重复'
              childElementPosition='right'
          >
            <Input onChange={val => setConfirmNewPassword(val)} placeholder='请重复输入您设置的新密码'/>
          </Form.Item>
        </>:<List.Item onClick={() => {setIsChangePwd(true)}}>修改密码</List.Item>}

      </List>

    </Form>

  </section>;
};

export default UserInfo;


